<template>
    <el-form ref="formRef" :inline="formConfig.inline || false" :model="formData" :rules="formConfig.rules || {}" :label-width="formConfig.labelWidth">
      <el-form-item
        v-for="item in formConfig.itemList"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
      >
      <!-- input -->
        <el-input 
          v-if="item.type == 'input'"
          v-model="formData[item.prop]"
          :placeholder="item.placeholder" 
          :clearable="item.clearable || true"
        />

        <!--  textarea -->
        <el-input 
          v-if="item.type == 'textarea'"
          type="textarea"
          :rows="4"
          v-model="formData[item.prop]"
          :placeholder="item.placeholder" 
          :clearable="item.clearable || true"
        />

        <!-- select -->
          <el-select
          v-if="item.type == 'select'"
          v-model="formData[item.prop]"
          :placeholder="item.placeholder" 
          :clearable="item.clearable || true"
          >
          <el-option 
            v-for="opt in item.option" 
            :key="opt[item.optionValue]" 
            :label="opt[item?.optionLabel ?? 'label']" 
            :value="opt[item?.optionValue ?? 'id']" 
          />
        </el-select>

        <!-- date -->
          <el-date-picker
          v-if="item.type == 'date'"
          type="date"
          v-model="formData[item.prop]"
          :placeholder="item.placeholder" 
          :clearable="item.clearable || true"
        />

      </el-form-item>

    </el-form>
</template>

<script setup name="user">
import { ref, reactive, toRaw, watchEffect } from "vue";

const props = defineProps({
  formData: {
    type: Object,
    default: {},
  },
  formConfig: {
    type: Object,
    default: {},
  },
})

const formRef = ref(null)

const reset = () => {
  formRef.value.resetFields()
}

const resetFields = () => {
  formRef.value.resetFields()
}

const validate = async(cb) => {
   return await formRef.value.validate((valid, fields) => {
    cb && cb(valid, fields)
   })
}

const validateP = () => {
  return new Promise((resove, reject) => {
    formRef.value.validate((valid, fields) => {
      if (valid) {
        resove(valid)
      } else {
        reject(fields)
      }
    })
  })
}

defineExpose({
  formRef,
  reset,
  resetFields,
  validate,
  validateP
})

</script>

<style lang="less" scoped>

.el-input {
  --el-input-width: 220px;
}

.el-select {
  --el-select-width: 220px;
}

</style>
